package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.service.SolrService;

@Service("solrService")
public class SolrServiceImpl implements SolrService {

	@Value("${solr.url}")
	private String solrURL;

	private static final Logger logger = LoggerFactory.getLogger(SolrServiceImpl.class);

	@Async
	@Override
	public void updateSolr(Long id, String name, String type) {
		SolrServer server = null;
		try {
			server = new CommonsHttpSolrServer(solrURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("id", id.toString()+"_"+type);
		doc.addField("name", name);
		doc.addField("type", type);
		try {
			server.add(doc);
			server.commit();
			logger.info("putting to solr search engine type: "+type+" name: "+name );
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	@Override
	public void updateSolr(Long id,  String type) {
		SolrServer server = null;
		try {
			server = new CommonsHttpSolrServer(solrURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			server.deleteByQuery("id:"+id+"_"+type.toLowerCase());
			server.commit();
			logger.info("delete from solr search engine id: "+id+"_"+type.toLowerCase() );
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
